<?php namespace App\Repositories\Eloquent\Money;

use App\Models\BalanceDetail;
use App\Models\User;
use App\Repositories\Money\BalanceRepositoryInterface;

class BalanceRepository implements BalanceRepositoryInterface
{
    /**
     * 用户余额
     *
     * @param $user_id
     *
     * @return mixed
     */
    public function balance($user_id)
    {
        return BalanceDetail::query()
            ->where('user_id', (int)$user_id)
            ->valid()
            ->sum('money');
    }

    /**
     * 记录平台余额消费记录
     *
     * @param        $flow_id
     * @param        $money
     * @param string $remark
     *
     * @return BalanceDetail
     */
    public function storePlatform($flow_id, $money, $remark = '')
    {
        return $this->store(User::PLATFORM_UID, $flow_id, $money, $remark);
    }

    /**
     * 记录余额消费记录
     *
     * @param        $user_id
     * @param        $flow_id
     * @param        $money
     * @param string $remark
     *
     * @return BalanceDetail
     */
    public function store($user_id, $flow_id, $money, $remark = '')
    {
        $model = new BalanceDetail();
        $model::unguard();
        $model->fill(compact('user_id', 'flow_id', 'money', 'remark'));
        $model->is_valid = BalanceDetail::VALID;

        $balance = $this->balance($user_id);
        //计算余额
        $model->balance = bcadd($balance, $money, 2);

        $model->save();

        return $model;
    }
}
